package com.loong.data.handler;

import com.alibaba.fastjson.JSON;
import com.loong.common.param.BaseIdParam;
import com.loong.common.rabbitmq.dto.GoodsCategoryDTO;
import com.loong.common.utils.TransformUtils;
import com.loong.data.common.backend.result.GoodsCategoryResult;
import com.loong.data.common.forehead.param.*;
import com.loong.data.common.forehead.result.GoodsCategoryForeheadResult;
import com.loong.data.model.GoodsCategoryModel;
import com.loong.data.repository.GoodsCategoryRepository;
import org.apache.commons.lang3.ObjectUtils;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @Description:
 * @Author: hzp
 * @Date: 2020-12-3 16:29
 */
@Component
public class GoodsCategoryHandler {
    @Resource
    private GoodsCategoryRepository goodsCategoryRepository;

    @Resource
    private RestHighLevelClient client;

    @Resource
    private ElasticsearchRestTemplate template;

    /**
     * 新增商品类型信息到es：MQ消费者中调用该方法
     *
     * @param goodsCategoryDTO 商品类型参数
     */
    public void saveGoodsCategoryModel(GoodsCategoryDTO goodsCategoryDTO) {
        goodsCategoryRepository.save(TransformUtils.transform(goodsCategoryDTO, GoodsCategoryModel.class));
    }

    /**
     * 更新商品类型信息到es：MQ消费者中调用该方法
     *
     * @param goodsCategoryDTO 商品类型参数
     */
    public void updateGoodsCategoryModel(GoodsCategoryDTO goodsCategoryDTO) {
        //创建更新请求
        UpdateRequest request = new UpdateRequest("goods_category", goodsCategoryDTO.getId().toString());
        //将要更新的数据以json格式封装到请求中
        request.doc(JSON.toJSONString(goodsCategoryDTO), XContentType.JSON);
        //执行更新请求的操作
        try {
            client.update(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id删除es中的商品类型信息：MQ消费者中调用该方法
     *
     * @param ids 商品类型信息id
     */
    public void deleteGoodsCategoryModelByIds(String ids) {
        if(ObjectUtils.isEmpty(ids))return;
        String[] idArrays = ids.split(",");
        Arrays.stream(idArrays).forEach(id -> goodsCategoryRepository.deleteById(Long.parseLong(id)));
    }


    /**
     * 前台根据店铺id查询商品类型 c端使用
     *
     * @param param 店铺id
     * @return 商品类型
     */
    public List<GoodsCategoryForeheadResult> findGoodsCategoryModelByShopId(BaseIdParam param) {
        GoodsCategoryForeHeadQueryParam goodsCategoryForeHeadQueryParam = GoodsCategoryForeHeadQueryParam.builder().shopId(param.getId()).build();
        List<GoodsCategoryDTO> goodsCategoryDTOS = this.commonPageQueryGoodsCategory(goodsCategoryForeHeadQueryParam);
        return TransformUtils.transformList(goodsCategoryDTOS,GoodsCategoryForeheadResult.class);
    }

    /**
     * 前台根据店铺id查询商品类型 后端使用
     *
     * @param param 店铺id
     * @return 商品类型
     */
    public List<GoodsCategoryResult> findGoodsCategoryModelByShopIdBackend(BaseIdParam param) {
        GoodsCategoryForeHeadQueryParam goodsCategoryForeHeadQueryParam = GoodsCategoryForeHeadQueryParam.builder().shopId(param.getId()).build();
        List<GoodsCategoryDTO> goodsCategoryDTOS = this.commonPageQueryGoodsCategory(goodsCategoryForeHeadQueryParam);
        return TransformUtils.transformList(goodsCategoryDTOS,GoodsCategoryResult.class);
    }
    /**
     * 公共方法：分页查询商品
     * @param param 查询和分页封装的参数
     * @return 商品信息集合
     */
    private List<GoodsCategoryDTO> commonPageQueryGoodsCategory(GoodsCategoryForeHeadQueryParam param) {
        PageForeheadParam pageParam = null;
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (ObjectUtils.isNotEmpty(param)){
            //构建查询条件
                if (ObjectUtils.isNotEmpty(param.getCategoryName())) {
                    //商品类型名称进行精确查询
                    boolQuery.must(QueryBuilders.matchPhraseQuery("categoryName", param.getCategoryName()));
                }
                if (ObjectUtils.isNotEmpty(param.getShopId())){
                    boolQuery.must(QueryBuilders.termQuery("shopId",param.getShopId()));
                }
            }else{
                boolQuery.must(QueryBuilders.matchAllQuery());
            }

        return executeQuery(boolQuery);
    }

    /**
     * 执行查询请求，并获得结果
     * @param queryBuilder 查询条件
     * @return 商品类型集合
     */
    private List<GoodsCategoryDTO> executeQuery(QueryBuilder queryBuilder){
        //存放商品信息的集合
        List<GoodsCategoryModel> modelList = new ArrayList<>();
        //构建查询条件
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .build();
        //获得查询的结果
        SearchHits<GoodsCategoryModel> hits = template.search(searchQuery, GoodsCategoryModel.class);
        List<SearchHit<GoodsCategoryModel>> hitList = hits.getSearchHits();
        for (SearchHit<GoodsCategoryModel> hit : hitList) {
            GoodsCategoryModel model = hit.getContent();
            modelList.add(model);
        }
        return TransformUtils.transformList(modelList,GoodsCategoryDTO.class);
    }


}
